import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条样式
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth' // 验权

const whiteList = ['/login'] // 不重定向白名单
router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    	/* 已登录*/
		if(to.path === '/login') {
			next({
				path: '/'
			})
			NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
		} else {
			if(store.getters.menu.length === 0) { //是否获取用户权限列表
				store.dispatch('GetMenuList').then(() => {
					store.dispatch('GenerateRoutes').then(() => {
						router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
						next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
					})
				})
				
			} else {
				next()
			}

		}
  } else {
    if(whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
		next()
	} else {
		next('/login') // 否则全部重定向到登录页
		NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
	}
	
	
	
  }
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
})
